
goog.provide('esn.client.BaseClient');

goog.require('goog.Uri');
goog.require('goog.json');


/**
 * @constructor
 */
esn.client.BaseClient = function(serviceName, xhrManager) {
  this.serviceName_ = serviceName;

  this.xhrManager_ = xhrManager;
};

esn.client.BaseClient.uniqueIdCounter_ = 0;

/**
 * @param {goog.Uri.QueryData} request
 * @param {function(Object)} callback
 */
esn.client.BaseClient.prototype.send = function(method, request, opt_callback) {
  var uri = new goog.Uri('/service');
  var query = new goog.Uri.QueryData();
  query.set('service', this.serviceName_);
  query.set('method', method);
  query.set('request', goog.json.serialize(request));

  this.xhrManager_.send(
      String(esn.client.BaseClient.uniqueIdCounter_++),
      uri.toString(),
      'POST',
      query.toString(),
      undefined,
      undefined,
      goog.bind(this.response_, this, opt_callback || null));
};

esn.client.BaseClient.prototype.response_ = function(callback, e) {
  var responseJson = e.target.getResponseJson();
  if ('error' in responseJson) {
    window.console.log(responseJson['error']['internal_message']);
  }
  if (callback) {
    callback(responseJson);
  }
};
